<?php
include('phpqrcode/qrlib.php');

$fg = "";
$copies = 1;
if (isset($_GET['copies'])) {
	if ($_GET['copies'] != "") {
		if (is_numeric($_GET['copies'])) {
			$copies = $_GET['copies'];
		}
	}
}

if (!isset($_GET['name'])) {
	echo "No Name";
	exit;
}

if (!isset($_GET['og'])) {
	echo "No OG";
	exit;
}

if (isset($_GET['fg'])) {
	if ($_GET['fg'] != "") {
		$fg = $_GET['fg'];
	}
}

$date = "";
if (!isset($_GET['date'])) {
	$date = date("Y-m-d");
} else {
	$date = $_GET['date'];
}

$name = $_GET['name'];
$og = $_GET['og'];

function resize_image($file, $w, $h, $crop=FALSE) {
    list($width, $height) = getimagesize($file);
    $r = $width / $height;
    if ($crop) {
        if ($width > $height) {
            $width = ceil($width-($width*($r-$w/$h)));
        } else {
            $height = ceil($height-($height*($r-$w/$h)));
        }
        $newwidth = $w;
        $newheight = $h;
    } else {
        if ($w/$h > $r) {
            $newwidth = $h*$r;
            $newheight = $h;
        } else {
            $newheight = $w/$r;
            $newwidth = $w;
        }
    }
    $src = imagecreatefrompng($file);
    $dst = imagecreatetruecolor($newwidth, $newheight);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

    return $dst;
}

//imagepng($img, "output.png");
//$o = `convert -trim filename.png`;

//echo imagepng($img);
$ww = wordwrap ("Name: $name~",22,"~");
$ww .= wordwrap ("O.G.: $og~",22,"~");
if ($fg != "") {
	$ww .= wordwrap ("F.G.: $fg~",22,"~");
	//calculate the A.B.V
	$abv = $og - $fg;
	$abv = $abv * 131;
	$abv = round($abv,3);
	$ww .= wordwrap ("A.B.V: $abv~",22,"~");
}
$ww .= wordwrap ("Date: $date~",22,"~");

$q = str_replace("~","\n",$ww);

QRcode::png($q, 'filename.png');
$img = resize_image('filename.png',130,130);

//$img =  imagecreatefrompng ('filename.png');

$im = imagecreate(300,173);
$background_color = imagecolorallocate($im, 255, 255, 255);
$text_color = imagecolorallocate($im, 0,0,0);
imagecopy($im, $img, 7, 0, 0, 0, 130, 130);

$e = explode("~",$ww);
if (sizeof($e) > 8) {
	echo "Too Much Data to print\n";
	exit;
}
for($i = 0;$i<sizeof($e);$i++) {
	if ($i == 0) { 
		$start = 20;
	} else {
		$start += 12;
	}
	imagestring($im, 3, 130, $start, $e[$i] , $text_color);
	//echo $e[$i];
}
imagepng($im, "output.png");
//imagepng($im);
imagedestroy($im);
$o = `convert -rotate 90 output.png o.png`;
$o = `sam2p o.png EPS: out.eps`;
//echo "Done";
for ($i = 0;$i<$copies;$i++) {
	$o = `/usr/bin/lpr -o landscape out.eps`;
	//echo $i . "<br />";
}
header("Content-Type: image/png");
echo file_get_contents("o.png");
?>
